<template>
  <div>
    <Row class="y_query_right">
<!--      <Button type="primary" icon="md-arrow-forward" class="y_condition" @click="testImport()">采集测试</Button>-->
<!--      <Button type="primary" icon="md-arrow-forward" class="y_condition" :disabled="noSelectedRows" @click="importToFormalLib()">导入正式库</Button>-->
<!--      <Divider></Divider>-->
<!--      <Select v-model="searchParam.hasImported" v-if="searchStateIsAudited" placeholder="是否已导入正式库" clearable class="y_condition" style="text-align: left;">-->
<!--        <Option :value="0">未导入</Option>-->
<!--        <Option :value="1">已导入</Option>-->
<!--      </Select>-->
      <Cascader v-model="searchParam.categories" :data="categoryTreeData" change-on-select placeholder="采集分类" class="y_condition" style="text-align: left;"></Cascader>
      <Input type="text" v-model.trim="searchParam.pCode" placeholder="货源编号" clearable class="y_condition"></Input>
      <Input type="text" v-model.trim="searchParam.titleEn" placeholder="产品名称" clearable class="y_condition"></Input>
      <Input type="url" v-model.trim="searchParam.sourceUrl" placeholder="采集链接" clearable class="y_condition" style="max-width: 300px; width: 300px;"></Input>
      <Input type="text" v-model.trim="searchParam.shopId" placeholder="供货商编号" clearable class="y_condition"></Input>
      <Input v-model.trim="searchParam.tag" class="y_condition" placeholder="产品标签"></Input>
      <Select v-model="searchParam.state" class="y_condition" clearable placeholder="审核状态" style="text-align: left;">
        <Option v-for="(item, index) in dict.productStates" :key="index" :value="item.value">{{item.label}}</Option>
      </Select>
      <Select v-model="searchParam.from" class="y_condition" style="text-align: left;" clearable placeholder="平台">
        <Option v-for="(item, index) in dict.productSources" :key="index" :value="item.value">{{item.label}}</Option>
      </Select>
      <Select v-model="searchParam.siteCode" class="y_condition" style="text-align: left;" placeholder="站点">
        <Option v-for="(item, index) in dict.siteCodes" :key="index" :value="item.value">{{item.label}}</Option>
      </Select>

      <Select v-model="searchParam.hasBanned" class="y_condition" style="text-align: left;" clearable placeholder="屏蔽状态">
        <Option :value="0">未屏蔽</Option>
        <Option :value="1">已屏蔽</Option>
      </Select>
      <Input type="text" v-model.trim="searchParam.author" placeholder="采集人" clearable class="y_condition"></Input>
      <Checkbox v-model="searchParam.isAuditable">可审核</Checkbox>
      <DatePicker type="daterange" :options="datePickerOptions" placement="bottom-end" :editable="false" placeholder="采集时间"
                  @on-change="changeTimeParam" @on-clear="clearTimeParam" class="y_condition" style="text-align: left; max-width: 200px; width: 200px;"></DatePicker>
      <Button type="primary" icon="md-search" class="y_condition" @click="search()">查询</Button>
      <Cascader  v-model="batchCategoryId" :data="categoryTreeData" change-on-select style="width: 250px;"></Cascader>
      <Select v-model="batchPriceUnit" style="width: 150px;">
        <Option v-for="(item, index) in dict.priceUnits" :key="index" :value="item.value">{{item.label}} - {{item.value}}</Option>
      </Select>


      <Button type="success" icon="md-cloud-upload" :disabled="selectedIds.length==0" @click="batchUpdate()" class="y_condition" >批量通过审核</Button>
    </Row>

<!--    <Table :columns="tableColumns" :data="productList" @on-selection-change="changeSelectedRows" border style="margin-top: 20px;"></Table>-->
    <div v-if="productList.length > 0" style="text-align: left; margin: 1rem 0 0 25px;">
      <Checkbox v-model="allCheck.isChecked" :indeterminate="allCheck.indeterminate" @on-change="toggleAllCheck" style="vertical-align: middle;">全选</Checkbox>
    </div>

    <List class="data-list" border>
      <div v-if="productList.length > 0">
        <CheckboxGroup v-model="selectedIds">
        <ListItem v-for="(item, index) in productList" :key="item.id" class="list-item">
          <Row style="width: 100%;">
            <Col :span="3" :xxl="3" :xl="4" :lg="5" :md="6" :sm="9" :xs="12" style="text-align: left; line-height: 100%;display: flex;align-items: center;">
              <div class="item-checkbox">
                <Checkbox :label="item.id" ><span></span></Checkbox>
              </div>
              <div style="width: 130px; text-align: center; margin: 0 auto;" @click="showBigImage(getProductOriginalImg(item))">
                <img :src="getProductImg(item)" style="max-width: 100%;"/>
              </div>
            </Col>
            <Col :span="21" :xxl="21" :xl="20" :lg="19" :md="18" :sm="16" :xs="14" style="padding-left: 0.5rem">
              <div class="item-top">
                <p style="font-weight: bold; text-align: left;">
                  <Tag :color="getStateColor(item)">{{getProductState(item)}}</Tag>
                  {{item.title}}
                </p>
                <Tag color="gray" v-if="item.hasBanned">已屏蔽</Tag>
              </div>

              <div class="item-content">
                <div>
                  <KeyValueView title="货源编号">
                    {{item.pCode}}
                  </KeyValueView>

                  <KeyValueView title="标签">
                   <span v-if="item.tags!=null && item.tags.length>0">{{item.tags.join("，")}}</span>
                    <span v-else>无</span>
                  </KeyValueView>

                  <br/>
                </div>
                <div>
                  <KeyValueView title="采集分类" v-if="item.categoryNames!=null && item.categoryNames.length > 0">{{item.categoryNames.join(" / ")}}</KeyValueView>
                  <KeyValueView title="计费重量" :value="getProductWeight(item)"></KeyValueView>
                  <KeyValueView title="是否有尺码表" :value="getHasSizeTable(item)"></KeyValueView>
                </div>
                <div>
                  <KeyValueView title="平台" :value="item.from"></KeyValueView>
<!--                  <KeyValueView title="供货商" v-if="item.store!=null">{{item.store.shopName}}</KeyValueView>-->
                  <KeyValueView title="供货商编号" :value="item.shopId"></KeyValueView>
                  <KeyValueView title="采集时间" :value="$tiyBJTime(item.createTime)"></KeyValueView>
                  <KeyValueView title="采集人" :value="item.author"></KeyValueView>
                </div>
                <div v-if="isItemBanned(item)" style="background: #f5f5f5;padding: 0.2rem 0.5rem;margin: 0.5rem 0">
                  <KeyValueView title="屏蔽人" :value="item.banInfo.employeeName"></KeyValueView>
                  <KeyValueView title="屏蔽时间" :value="$tiyBJTime(item.banInfo.banTime)"></KeyValueView>
                  <KeyValueView title="屏蔽原因" :value="item.banInfo.reason"></KeyValueView>

                </div>
                <div v-else-if="isItemAudited(item)">
                  <KeyValueView title="审核人" :value="item.auditInfo.employeeName"></KeyValueView>
                  <KeyValueView title="审核时间" :value="$tiyBJTime(item.auditInfo.auditTime)"></KeyValueView>
                  <KeyValueView title="备注" :value="item.auditInfo.desc"></KeyValueView>
                </div>
              </div>

              <div class="item-bottom">
                <Tag color="geekblue" v-if="!belongToCurrentStation(item)">非本站产品,不可编辑</Tag>
                <Button type="info" ghost size="small" icon="md-arrow-forward" @click="showImportDialog(item)" v-if="isItemAudited(item) && !isItemBanned(item)" title="导入正式库">导入</Button>
                <Button type="error" ghost size="small" icon="md-eye-off" @click="showBanModal(item)" v-if="!isItemBanned(item)" v-show="belongToCurrentStation(item)">屏蔽</Button>
                <Button type="success" ghost size="small" icon="md-undo" @click="cancelBanProduct(item)" v-if="isItemBanned(item)" v-show="belongToCurrentStation(item)">取消屏蔽</Button>
                <Button type="primary" ghost size="small" icon="md-create" @click="showModifyModal(item)" v-show="belongToCurrentStation(item)">{{getEditButtonText(item)}}</Button>
                <Button type="error" ghost size="small" icon="md-trash" @click="deleteProduct(item.id)">删除</Button>
              </div>
            </Col>
          </Row>
        </ListItem>
        </CheckboxGroup>
      </div>
      <div v-else>
        <ListItem>
          <div style="width: 100%; text-align: center; color: #ccc;">暂无数据</div>
        </ListItem>
      </div>
    </List>
    <div style="text-align: right; margin-top: 20px;">
      <Page :total="page.total" :page-size="page.pageSize" :current="page.pageNum" @on-change="pageNumChange"
            @on-page-size-change="pageSizeChange" :page-size-opts="page.options"
            show-sizer show-elevator show-total></Page>
    </div>

    <!-- 修改产品信息 -->
    <Modal v-model="status.modifyModal.isShow" :mask-closable="false" title="审核或编辑" :width="1200">
<!--      <Divider size="small" orientation="left">产品概况</Divider>-->
      <Form ref="impProductForm" :model="productParam" :label-width="120" inline label-colon>
        <div class="modal_base_div">
          <div class="modal_base_div_title">产品基本属性：</div>

          <FormItem label="货源编码" prop="pCode">
            {{productParam.pCode}}
          </FormItem>
          <FormItem label="采集链接" prop="sourceUrl">
            <a :href="productParam.sourceUrl" target="_blank" :title="productParam.sourceUrl">{{productParam.sourceUrl}}</a>
          </FormItem>


          <FormItem label="产品名称" prop="titleEn" required class="one-line" :show-message="false">
            <Input v-model="productParam.title">
              <Button slot="append" @click="translateText()" title="翻译">翻译</Button>
            </Input>
            <Input v-model.trim="productParam.titleEn" :maxlength="150" style="margin-top: 0.5rem">
              <Button slot="append" @click="nameFirstUpperCase()" title="自动校验大小写">Aa ({{productParam.titleEn.length}}/150)</Button>
            </Input>
<!--            <span class="under-tip">{{productParam.title}}</span>-->
          </FormItem>

          <br/>

          <FormItem label="运费核算重量" prop="weight" required :label-width="140" :show-message="false">
            <Input type="text" v-model="productParam.weight" style="width: 200px;">
              <span slot="append">g</span>
            </Input>
            <div style="line-height: 20px; margin-top: 5px;">
              <span class="under-tip" style="display: block;" v-for="(item, index) in getWeightAttrs(productParam.attrs)" :key="index">{{item.name}}:{{item.value}}</span>
            </div>
          </FormItem>

          <FormItem label="采集分类" prop="categories" required :show-message="false">
            <Cascader  v-model="productParam.categories" :data="categoryTreeData" change-on-select style="width: 250px;"></Cascader>
          </FormItem>

          <br/>

          <FormItem label="采集标签" prop="tags">
            <Select v-model="productParam.tags" multiple filterable allow-create @on-create="createTag"
                    placeholder="用户不可见,可中文" style="width: 250px;">
              <Option v-for="(tag, index) in status.modifyModal.tagList" :key="index" :value="tag">{{tag}}</Option>
            </Select>
          </FormItem>

          <FormItem label="适用性别" prop="gender">
            <Select v-model="productParam.gender" style="width: 200px;">
              <Option value="未知">未知</Option>
              <Option value="男">男</Option>
              <Option value="女">女</Option>
              <Option value="其它">其它</Option>
              <Option value="中性">中性</Option>
            </Select>
          </FormItem>

          <FormItem label="其他货源" prop="otherSourceUrls" class="one-line">
            <Button type="info" ghost icon="md-add" @click="showOtherSourceModal()">新增备用货源</Button>
            <div v-for="(url, index) in productParam.otherSourceUrls" :key="index" style="margin-top: 20px;">
<!--              <span class="item-name">备用货源-{{index+1}}: </span>-->
              <Input type="text" v-model.trim="productParam.otherSourceUrls[index]" placeholder="备用货源链接" style="max-width: 50%" class="item-input-large"></Input>
              <Button @click="deleteSourceUrl(index)">删除</Button>
            </div>
          </FormItem>

        </div>

        <!-- 产品价格 -->
        <div class="modal_base_div">
          <div class="modal_base_div_title">产品价格：</div>
          <FormItem label="价格单位" prop="priceUnit" :label-width="140" required :show-message="false">
            <Select v-model="productParam.priceUnit" style="width: 150px;">
              <Option v-for="(item, index) in dict.priceUnits" :key="index" :value="item.value">{{item.label}} - {{item.value}}</Option>
            </Select>
          </FormItem>
          <Alert type="warning">1. 设置价格时,单位均为人民币   2.运费成本处输入总成本, 例如二挡起订5件需20元运费, 则这里需填写20, 产品价格计算时运费会自动处理: 20/5=4元 </Alert>
          <KeyValueView title="采集备注" :value="productParam.extra"></KeyValueView>
          <FormItem prop="prices" v-for="(item, index) in productParam.prices" :key="index" class="one-line" :label-width="80" style="margin-top: 10px;">
            <span slot="label" class="item-label">{{'第'+(index+1)+'档'}}</span>
            <span class="item-name item-name-count">起订量：</span>
            <Input type="number" v-model="item.begin" style="max-width: 70px" @on-change="computeSumPrice(index)"></Input>
            &nbsp;&nbsp;=>&nbsp;&nbsp;
            <span class="item-name ">采集单价:&nbsp;&nbsp; </span>
            <Input type="number" v-model="item.price" :append="currency" @on-blur="computeSumPrice(index)" placeholder="价格" class="item-input-mini" @on-change="computeSumPrice(index)"></Input>
            <span class="item-name"> + 运费成本:&nbsp;&nbsp;</span>
            <Input type="number" ref="totalShippingCost"  v-model="item.totalShippingCost" @on-blur="computeSumPrice(index)" placeholder="总成本" class="item-input-mini" @on-change="computeSumPrice(index)"></Input>
            <span class="item-name">/{{item.begin}} </span>
                  <span style="color: #bdbdbd;font-size: 12px;padding: 0 0.5rem" v-text="'(均摊'+item.shippingCost+'元/件)'"></span>
            <span> =  保底价格:</span> <span>{{item.usdPrice}}美元</span>
            <Button @click="deletePrice(index)"  style="margin-left: 1rem">删除</Button>
            <div style="padding: 0.5rem 0;color: palevioletred">
              <span v-show="item.begin<=0" style="padding: 0 0.25rem">起订量不可为{{ item.begin }};</span>
              <span v-show="item.price<=0"  style="padding: 0 0.25rem">采购单价不可为{{item.price}};</span>
              <span v-show="item.totalShippingCost<=0"  style="padding: 0 0.25rem">运费成本不可为{{ item.totalShippingCost }};</span>
              <span v-show="index>0 && productParam.prices[index-1].begin>=item.begin" style="padding: 0 0.25rem">档位起订量低于上一档了;</span>
              <span v-show="index>0 && productParam.prices[index-1].usdPrice<=item.usdPrice" style="padding: 0 0.25rem">档位价格高于上一档了;</span>
            </div>
          </FormItem>
          <Button type="info" ghost icon="md-add" @click="addPrice()">新增一档起订量与价格</Button>
        </div>

        <!-- 尺码表 -->
        <div class="modal_base_div">
          <div class="modal_base_div_title">产品尺码表（可选）：
            <!--            <Button type="primary" icon="md-add" @click="addSizeTable()" style="margin-left: 20px;" v-if="!productParam.hasSizeTable">新增</Button>
                        <Button type="error" icon="md-trash" @click="deleteSizeTable()" style="margin-left: 20px;" v-else>删除</Button>-->
          </div>
          <div>
            <SizeTableTransform v-model="productParam.sizeTable"></SizeTableTransform>
          </div>
        </div>

        <!-- 产品图片 -->
        <div class="modal_base_div">
          <div class="modal_base_div_title">产品图片：
            <Button type="error" icon="md-trash" @click="removeNonExistImages(productParam)">一键清空错误图片</Button>
            <Upload :action="uploadUrl" :data="uploadParam" :on-progress="uploadProgress"
                    :on-success="uploadSuccess" :on-error="uploadError" :show-upload-list="false"
                    multiple style="display: inline-block; margin-left: 10px;">
              <Button type="primary" icon="md-cloud-upload">上传图片</Button>
            </Upload>
            <Button type="primary" icon="md-images" @click="recollectImages(productParam)" style="margin-left: 10px;">重新采集图片</Button>
          </div>
          <span style="color: #757575">如何替换图片: 上传一个同名的图片即可, 例如上传一个main_0.jpg的图片可以覆盖掉现有的main_0.jpg</span>
          <FormItem label="主图" prop="mainImgs" class="one-line">
            <Card v-for="(img, index) in productParam.mainImgs" :key="index" class="image-card" style="height: 245px;">
              <div class="image-box" @click="showBigImage(yunPath+img.colorImg)">
                <img :src="getListImgUrl(img.colorImg, productParam)" alt="图片可能还未上传"/>
              </div>
              <div style="text-align: center">{{ img.colorImg.substring(img.colorImg.indexOf('/')+1) }}</div>
              <div slot="title">
                <span v-if="index == 0">橱窗图</span>
                <a href="javascript:void(0)" @click="moveToFirst(productParam.mainImgs, index)" v-else>设为橱窗图</a>
              </div>
              <div slot="extra" class="extra">
                <Icon type="md-close-circle" @click="deleteImage(1, index)"></Icon>

              </div>
            </Card>
          </FormItem>
          <FormItem label="详情图" prop="productImgs" class="one-line">
            <Card v-for="(img, index) in productParam.productImgs" :key="index" class="image-card">
              <div class="image-box" @click="showBigImage(yunPath+img.colorImg)">
                <img :src="yunPath + img.colorImg + '?v=' + imgParam" alt="图片可能还未上传"/>
              </div>
              <div style="text-align: center">{{ img.colorImg.substring(img.colorImg.indexOf('/')+1) }}</div>
              <div slot="extra" class="extra">
                <Icon type="md-close-circle" @click="deleteImage(2, index)"></Icon>
              </div>
            </Card>
          </FormItem>
        </div>



        <!-- 产品属性 -->
        <div class="modal_base_div">
          <div class="modal_base_div_title">产品属性列表：</div>


          <FormItem v-for="(item, index) in productParam.attrs" :key="index" class="one-line">
            <span slot="label" class="item-label">{{" #"+(index+1)+"："}}</span>
            <div class="attr-item">
              <div class="one-line" v-if="isBrandsAttr(item)">
                <span class="attr-name">属性名：</span><Input type="text" v-model="item.nameEn" readonly class="item-input" :maxlength="100" show-word-limit></Input>
                <span class="attr-name"></span><span class="under-tip">{{item.name}} (不可修改)</span>
              </div>
              <div class="one-line" v-else>
                <span class="attr-name">属性名：</span><Input type="text" v-model="item.nameEn" class="item-input" :maxlength="100" show-word-limit></Input>
                <span class="attr-name"></span><span class="under-tip">{{item.name}}</span>
              </div>
            </div>
            <div class="attr-item">
              <div class="one-line" v-if="isBrandsAttr(item)">
                <span class="attr-name">属性值：</span><Select v-model="item.valueEn" filterable allow-create clearable @on-create="createBrand" @on-change="brand=>changeBrand(brand, item)" class="item-input"><Option v-for="brand in status.modifyModal.brandList" :key="brand" :value="brand">{{brand}}</Option></Select>
                <span class="attr-name"></span><span class="under-tip">{{item.value}}</span>
              </div>
              <div class="one-line" v-else>
                <span class="attr-name">属性值：</span><Input type="text" v-model="item.valueEn" class="item-input" :maxlength="200" show-word-limit></Input>
                <span class="attr-name"></span><span class="under-tip">{{item.value}}</span>
              </div>
            </div>
            <div class="item-button" v-if="!isBrandsAttr(item)">
              <Button @click="deleteAttribute(index)">删除</Button>
            </div>
          </FormItem>
          <Button type="info" ghost icon="md-add" @click="addAttribute()">新增产品属性</Button>
        </div>

        <!-- 产品色卡 -->
<!--        <div class="modal_base_div">
          <div class="modal_base_div_title">产品色卡：</div>
          <Table :columns="colorColumns" :data="productParam.colors" border></Table>
        </div>-->

        <div class="modal_base_div">
          <div class="modal_base_div_title">产品色卡列表：<Checkbox v-model="hideColorSizes" style="margin-left: 10px;">不显示尺码</Checkbox></div>
          <List border>
            <ListItem v-for="(item,index) in productParam.colors" style="padding-top: 30px; padding-bottom: 30px;">
              <Row style="width: 100%;">
                <Col :span="3">
                  <div class="one-line" style="text-align: center;">
                    <img :src="getListImgUrl(item.colorImg, productParam)" style="max-width: 100px" @click.stop="showBigImage(yunPath + item.colorImg)">
                  </div>
                  <div class="color-buttons">
                    <Button type="primary" icon="md-create" size="small" @click="showModifyColorModal(index)">修改</Button>
                    <Button type="error" icon="md-trash" size="small" @click="deleteProductColor(index)">删除</Button>
                  </div>
                </Col>
                <Col :span="20" style="margin-left: 20px;">
                  <div class="one-line">
                    <KeyValueView title="顺序">
                      <Input type="number" v-model="item.position" @on-blur="sortColors" class="item-input-mini"></Input>
                    </KeyValueView>

                    <KeyValueView :title="item.name">
                      <Input type="text" v-model="item.nameEn" class="item-input" style="margin-left: 5px;"></Input>
                    </KeyValueView>
                  </div>

                  <div v-if="item.sizes!=null"  style="margin: 1rem 0;" v-show="!hideColorSizes">
                    <Divider/>
                    <div v-for="(size, sizeIndex) in item.sizes" :key="sizeIndex"  class="one-line" style="padding: 0.5rem 0" >
                      <KeyValueView :title="size.name">
                        <Input type="text" v-model.trim="size.nameEn" class="item-input" style="margin-left: 5px;" :maxlength="40" show-word-limit>
                        </Input>
                      </KeyValueView>
                      <Button @click="modifyOtherColorSizes(size.name, size.nameEn)" v-if="isNotEmpty(size.name)">同步修改其他色卡</Button>
                      <Button type="error" @click="deleteColorSize(item.sizes, sizeIndex)" style="margin-left: 1rem">删除</Button>

                    </div>
                    <Button type="info" ghost icon="md-add" @click="addColorSize(item.sizes)">新增尺码</Button>
                  </div>
<!--                  <div class="one-line" style="margin-top: 10px; text-align: right;">
                    <Button type="primary" icon="md-create" size="small" @click="showModifyColorModal(index)" style="margin-top: 10px;">修改</Button>
                    <Button type="error" icon="md-trash" size="small" @click="deleteProductColor(index)" style="margin-top: 10px;">删除</Button>
                  </div>-->
                </Col>
              </Row>
            </ListItem>
          </List>
        </div>

        <!-- 审核备注 -->
        <div class="modal_base_div">
          <div class="modal_base_div_title">审核备注：</div>
          <FormItem :label-width="0" class="one-line">
            <Input type="textarea" v-model="productParam.auditInfo.desc" :rows="4" placeholder="内部使用,可中文"></Input>
          </FormItem>
        </div>
      </Form>

      <div slot="footer">
        <Button @click="hideModifyModal()" style="margin-right: 10px;">取消</Button>
        <Button type="primary" @click="modifyProductAfterAudited()" v-if="isAudited">保存</Button>
        <SplitButton @click="modifyProduct()" @click-item="auditProduct" v-else>
          保存
          <DropdownMenu slot="list" v-once>
            <DropdownItem name="pass">保存并通过审核</DropdownItem>
          </DropdownMenu>
        </SplitButton>
      </div>
    </Modal>

    <!-- 查看大图 -->
    <Modal v-model="bigImage.isShow" title="查看图片" footer-hide :width="600">
      <div class="big-img-box">
        <img :src="bigImage.src+'?v='+imgParam" alt="图片加载失败">
      </div>
    </Modal>

    <!-- 修改色卡 -->
    <Modal v-model="status.modifyColorModal.isShow" title="色卡详情" :mask-closable="false" :width="800">
      <Form ref="impProductColorForm" :label-width="120" :inline="true" label-colon>
        <div class="modal_base_div">
          <div class="modal_base_div_title">基本属性：</div>
          <FormItem label="色卡名" :label-width="80">
            <Input type="text" v-model="colorParam.nameEn"></Input>
            <span style="color: #888"> {{colorParam.name}}</span>
          </FormItem>
          <FormItem label="色卡排序">
            <Input type="number" v-model="colorParam.position" style="width: 3rem"></Input>
          </FormItem>
        </div>
        <div class="modal_base_div">
          <div class="modal_base_div_title">色卡图片：</div>
          <FormItem label="色卡图" :label-width="80" class="one-line">
            <Button type="primary" icon="md-swap" @click="showProductImageSelection(3)">更换</Button>
            <div style="margin-top: 10px;">
              <Card class="image-card">
                <div class="image-box" @click="showBigImage(yunPath+colorParam.colorImg)">
                  <img :src="yunPath + colorParam.colorImg + '?v=' + imgParam" alt="图片可能还未上传"/>
                </div>
<!--                <div slot="extra" class="extra">
                  <Icon type="md-close-circle" @click="deleteImage(3, index)"></Icon>
                </div>-->
              </Card>
            </div>
          </FormItem>
          <FormItem label="明细图" :label-width="80" class="one-line">
            <Button type="primary" icon="md-image" @click="showProductImageSelection(4)">选择图片</Button>
            <div style="margin-top: 10px;">
              <Card v-for="(img, index) in colorParam.detailImgs" :key="index" class="image-card">
                <div class="image-box" @click="showBigImage(yunPath+img)">
                  <img :src="yunPath + img + '?v=' +imgParam" alt="图片可能还未上传"/>
                </div>
                <div slot="extra" class="extra">
                  <Icon type="md-close-circle" @click="deleteImage(4, index)"></Icon>
                </div>
              </Card>
            </div>
          </FormItem>
        </div>
        <div class="modal_base_div">
          <div class="modal_base_div_title">色卡尺码与库存：</div>
          <FormItem class="one-line" v-for="(size, index) in colorParam.sizes" :key="index" :label-width="100">
            <span slot="label">尺码名称：</span>
            <div class="size-item">
              <div class="one-line">
                <Input type="text" v-model="size.nameEn" class="item-input-common"></Input><br/>
                <span class="under-tip">{{size.name}}</span>
              </div>
            </div>
            <div class="size-item">
              <div class="one-line">
                <span class="size-name">库存：</span><Input type="text" v-model="size.stock" class="item-input-small"></Input>
              </div>
            </div>
            <div class="item-button">
              <Button @click="deleteSize(index)">删除</Button>
            </div>
          </FormItem>
          <Button type="info" ghost icon="md-add" @click="addSize()">新增尺码</Button>
        </div>
      </Form>
      <div slot="footer">
        <Button @click="hideModifyColorModal()">取消</Button>
        <Button type="primary" @click="modifyProductColor()">确定</Button>
      </div>
    </Modal>

    <!-- 图片选择弹窗 -->
    <Modal v-model="status.imageSelectModal.isShow" title="选择图片" :mask-closable="false" width="700" footer-hide>
      <ImpProductImgSelect
        :product-code="productCode"
        :is-single-select="isSingleSelect(status.imageSelectModal.type)"
        @okClick="selectImages"
        @cancelClick="hideProductImageSelection">
      </ImpProductImgSelect>
    </Modal>

    <!-- 填写屏蔽备注 -->
    <Modal v-model="status.banModal.isShow" title="屏蔽原因" :mask-closable="false">
      <Form ref="banForm" :label-width="100" inline label-colon>
        <FormItem label="屏蔽原因">
          <Input type="textarea" v-model="banParam.reason" :rows="5" style="width: 350px;"></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="hideBanModal()">取消</Button>
        <Button type="primary" @click="banProduct()">确定</Button>
      </div>
    </Modal>

    <!-- 导入正式库弹窗 -->
    <Modal width="60%" v-model="importStatus.isShow" title="导入设置" :mask-closable="false">
      <import-dialog :import-param="importParam"></import-dialog>
      <div slot="footer">
        <Button @click="hideImportDialog()">取消</Button>
        <Button type="primary" @click="importProducts()">导入</Button>
      </div>
    </Modal>

    <!-- 新增备用货源弹窗 -->
    <Modal v-model="otherSourceModal.isShow" title="其它货源" :mask-closable="false">
      <Form>
        <FormItem>
          <Input v-model="otherSourceUrl"></Input>
          <span class="under-tip">系统会自动对链接进行精简格式化</span>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="hideOtherSourceModal()">取消</Button>
        <Button type="primary" @click="addSourceUrl()">添加</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import productData from "./js/product/productData";
import {
  banProducts, cancelBanProducts,
  deleteProduct, initPageInfo,
  // importToFormalLib,
  modifyProduct, queryMongoCategories,
  queryProductList, removeNonExistImages,
  saveProductTags, recollectImages,modifyBatchUpdateProduct
} from "./js/product/productFuns"
import axios from "axios";
import qs from "qs";
import SizeTableTransform from "./sizeTableTransform/SizeTableTransform";
import {isEmpty, isNotEmpty, translateText} from "../js/commonUtils";
import ImpProductImgSelect from "./imageSelection/ImpProductImgSelect";
import SplitButton from "./SplitButton/SplitButton";
import KeyValueView from "../widgets/KeyValueView";
import ApiBase from "../../api/moudles/ApiBase";
import importData from "./js/productImport/importData";
import ImportDialog from "./importDialog/ImportDialog";
import {importProducts, resetImportParams} from "./js/productImport/importFuns";

export default {
  name: "ProductList",
  components: {ImportDialog, KeyValueView, SplitButton, ImpProductImgSelect, SizeTableTransform},
  data() {
    return {
      yunPath: this.$store.getters.aliImgPrefix+"products/",
      station: this.$store.getters.siteInfo,
      currency: "¥",
      dict: productData.dict,
      searchParam: productData.tParam.searchParam,
      productList: productData.tData.list,
      selectedRows: [],
      page: productData.tPage.listPage,
      status: productData.tStatus,
      productParam: productData.tParam.modifyParam,
      colorParam: productData.tParam.colorParam,
      tagsParam: productData.tParam.tagsParam,
      banParam: productData.tParam.banParam,
      bigImage: {
        isShow: false,
        src: "",
      },
      productCode: "",
      categoryTreeData: [],
      datePickerOptions: productData.dict.datePickerOptions,
      uploadUrl: this.$apiImpProduct.getUploadUrl(),
      imgParam: new Date().getTime(),
      hideColorSizes: false,
      importParam: importData.tParam.importParam,
      importStatus: importData.tStatus.profitRatioModal,
      otherSourceModal: {
        isShow: false,
      },
      otherSourceUrl: "",
      selectedIds: [],
      allCheck: {
        isChecked: false,
        indeterminate: false,
      },
      batchCategoryId:"",
      batchPriceUnit:"piece"

    }
  },
  computed: {
    tableColumns() {
      let self = this;
      return [
        {type: "selection", width: 60, fixed: "left"},
        {title: "序号", width: 80, align: "center", type: "index", fixed: "left"},
        {title: "货源编号", width: 150, align: "center", render: function (h, params) {
            return h("a", {
              attrs: {href: params.row.sourceUrl, target: "_blank"},
            }, params.row.pCode);
          }
        },
        {title: "图片", width: 150, align: "center", render: function (h, params) {
            // let yunPath = self.yunPath;
            let imgUrl = self.getProductImg(params.row);
            return h("img", {
              attrs: {src: imgUrl,},
              style: {display: "inline-block", maxHeight: "80px", maxWidth: "80px", verticalAlign: "middle", margin: "5px;"},
              on: {
                click() {
                  self.showBigImage(imgUrl);
                }
              }
            });
          }
        },
        {title: "产品名称", minWidth: 300, align: "center", key:"title"},
        {title: "标签", width: 200, align: "center", render: function (h, params) {
            if(params.row.tags==null || params.row.tags.length==0) {
              return "";
            }
            let tags = [];
            for(let tag of params.row.tags) {
              tags.push(h("Tag", {props: {color: "purple"}}, tag));
            }
            return h("div", tags);
          }
        },
        {title: "货源", width: 150, align: "center", key:"from"},
        // {title: "货源链接", width: 300, align: "center", key:"sourceUrl"},
        // {title: "运费"+self.currency, width: 150, align: "center", key:"shippingFee"},
        {title: "采集时间", width: 180, align: "center", render: function (h, params){
            return h("div", self.$tiyBJTime(params.row.createTime));
          }
        },
        {title: "状态", width: 100, align: "center", render: function (h, params) {
            return h("div", self.$tiyBJTime(params.row));
          }
        },
        {title: "操作", width: 120, align: "center", fixed: "right", render: function (h, params) {
            return h("div", [
              h("Button", {
                props: {type: 'primary', size: 'small', icon: "md-create"},
                style: {marginRight: '10px',marginTop:'6px',marginBottom:'6px'},
                on: {
                  click: () => {
                    self.showModifyModal(params.row);
                  }
                }
              }, self.getEditButtonText(params.row)),
              // h("Button", {
              //   props: {type: 'primary', size: 'small', icon: "md-pricetags"},
              //   style: {marginRight: '10px',marginTop:'6px',marginBottom:'6px'},
              //   on: {
              //     click: () => {
              //       self.showModifyTagsModal(params.row);
              //     }
              //   }
              // }, "标签"),
              h("Button", {
                props: {type: 'error', size: 'small', icon: "md-trash"},
                style: {marginRight: '10px',marginTop:'6px',marginBottom:'6px'},
                on: {
                  click: () => {
                    self.deleteProduct(params.row.id);
                  }
                }
              }, "删除"),
            ]);
          }
        },
      ];
    },
    noSelectedRows() {
      return this.selectedRows == null || this.selectedRows.length == 0;
    },
    colorColumns() {
      let self = this;
      return [
        // {type: "selection", width: 60},
        {title: "排序", width: 100, align: "center", key: "position"},
        {title: "色卡名称", width: 200, align: "center", key:"name"},
        {title: "色卡名称(英文)", width: 250, align: "center", key:"nameEn"},
        {title: "色卡图片", width: 120, align: "center", render: function (h, params){
            let imgUrl = self.yunPath + params.row.colorImg;
            return h("img", {
              attrs: {src: imgUrl, alt:"图片加载失败，可能还未上传"},
              style: {display: "inline-block", maxHeight: "80px", maxWidth: "80px", verticalAlign: "middle", margin: "5px;"},
              on: {
                click() {
                  self.showBigImage(imgUrl);
                }
              }
            });
          }
        },
        {title: "明细图", width: 150, align: "center", render(h, params){
            let imageCount = params.row.detailImgs==null?0:params.row.detailImgs.length;
            return h("a", {
              attrs: {href: "javascript:void(0);"},
              on: {
                click() {
                  self.showModifyColorModal(params.index);
                }
              }
            }, imageCount);
          }
        },
        {title: "综合操作", minWidth: 200, align: "center", render: function (h, params) {
            return h("div", [
              h("Button", {
                props: {type: 'primary', size: 'small', icon: "md-create"},
                style: {marginRight: '10px',marginTop:'6px',marginBottom:'6px'},
                on: {
                  click: () => {
                    self.showModifyColorModal(params.index);
                  }
                }
              }, "修改"),
              h("Button", {
                props: {type: 'error', size: 'small', icon: "md-trash"},
                style: {marginRight: '10px',marginTop:'6px',marginBottom:'6px'},
                on: {
                  click: () => {
                    self.deleteProductColor(params.index);
                  }
                }
              }, "删除"),
            ]);
          }
        },
      ];
    },
    isAudited() {
      return this.productParam.state == productData.dict.stateAudited;
    },
    searchStateIsAudited() {
      return this.searchParam.state == productData.dict.stateAudited;
    },
    uploadParam() {
      let requestMsg = ApiBase.createRequestMsg({pCode: this.productParam.pCode});
      return {requestMsg: JSON.stringify(requestMsg)};
    }
  },
  methods: {
    getProductOriginalImg(row) {
      let imgOriginal = "";
      if(row.colors != null && row.colors.length > 0) {
        imgOriginal = row.colors[0].colorImg;
      }
      return isEmpty(imgOriginal)?"":this.yunPath+imgOriginal;
    },
    getProductImg(row) {
      let imgOriginal = this.getProductOriginalImg(row);
      if(isEmpty(imgOriginal)) {
        return "";
      }
      if(this.isItemAuditing(row) || this.isItemAudited(row)) {
        let imgUrl = imgOriginal.substring(0, imgOriginal.lastIndexOf("/"))+"/200w"+imgOriginal.substring(imgOriginal.lastIndexOf("/"))
        return imgUrl;
      }
      return imgOriginal + "?v="+this.imgParam;
    },
    getStateColor(product) {
      if(product.state === this.dict.stateNew) {
        return "error";
      }
      if(product.state === this.dict.stateAuditing) {
        return "warning";
      }
      if(product.state === this.dict.stateAudited) {
        return "success";
      }
    },
    translateText() {
      let params = {text: productData.tParam.modifyParam.title, caseType: 1, source: "zh", target: "en"};
      translateText(this, params, this.setTitleEn)
    },
    setTitleEn(titleEn) {
      productData.tParam.modifyParam.titleEn = titleEn;
    },
    nameFirstUpperCase() {
      productData.tParam.modifyParam.titleEn = this.$yFirstUpperCase(productData.tParam.modifyParam.titleEn).ResetBlank()
    },
    showOtherSourceModal() {
      this.otherSourceUrl = "";
      this.otherSourceModal.isShow = true;
    },
    hideOtherSourceModal() {
      this.otherSourceModal.isShow = false;
    },
    addSourceUrl() {
      if(isEmpty(this.otherSourceUrl)) {
        this.$Message.warning({content: "货源链接不能为空", duration: 3});
        return;
      }
      let otherSourceUrl = this.formatSourceUrl(this.otherSourceUrl);
      if(isEmpty(otherSourceUrl)) {
        return;
      }
      productData.tParam.modifyParam.otherSourceUrls.push(otherSourceUrl);
      this.hideOtherSourceModal();
    },
    formatSourceUrl(url) {
      if(url.indexOf("1688.com") > -1 || url.indexOf("aliexpress.com") > -1 || url.indexOf("alibaba.com") > -1) {//1688,速卖通，alibaba
        if(url.indexOf("?") > -1) {
          url = url.substring(0, url.indexOf("?"));
        }
        if(!url.endsWith(".html")) {
          this.$Message.warning({content: "货源链接格式错误，请检查后重试", duration: 3});
          return "";
        }
        url = url.replace( /(aliexpress.[a-z]*\/)/,'aliexpress.com/');
        url = url.replace( /([a-z\.]*aliexpress)/,'www.aliexpress');
        url = url.replace( /(detail.1688.[a-z]*\/)/,'detail.1688.com/');
        url = url.replace(/([a-z\.]*detail.1688)/,'detail.1688');
        return url;
      }
      if(url.indexOf("yangkeduo.com") > -1 || url.indexOf("weidian.com") > -1) {//拼多多,微店
        if(url.indexOf("?") < 0) {
          this.$Message.warning({content: "货源链接格式错误，请检查后重试", duration: 3});
          return "";
        }
        let productId = this.getProductIDFromUrl(url);
        if(isEmpty(productId)) {
          this.$Message.warning({content: "货源链接格式错误，请检查后重试", duration: 3});
          return "";
        }
        if(url.indexOf("yangkeduo.com") > -1) {
          return url.substring(0, url.indexOf("?")) + "?goods_id="+productId;
        }
        if(url.indexOf("weidian.com") > -1) {
          return url.substring(0, url.indexOf("?")) + "?itemID="+productId;
        }
      }
      this.$Message.warning({content: "货源链接格式错误，请检查后重试", duration: 3});
      return "";
    },
    getProductIDFromUrl(url) {
      if(url.indexOf("?") > -1) {
        if(!url.endsWith("?")) {
          let paramPairsStr = url.substring(url.indexOf("?")+1);
          let paramPairs = paramPairsStr.split("&");
          if(paramPairs.length >  0) {
            for(let paramPairStr of paramPairs) {
              let paramPair = paramPairStr.split("=");
              if(paramPair.length == 2) {
                if(paramPair[0] == "itemID" || paramPair[0] == "goods_id") {
                  return paramPair[1];
                }
              }
            }
          }
        }
      }
      return "";
    },
    deleteSourceUrl(index) {
      productData.tParam.modifyParam.otherSourceUrls.splice(index, 1);
    },
    isItemAuditing(item) {
      return item.state == this.dict.stateAuditing;
    },
    isItemAudited(item) {
      return item.state == this.dict.stateAudited;
    },
    isItemBanned(item) {
      return item.hasBanned;
    },
    getEditButtonText(product) {
      if(product.state === productData.dict.stateAudited) {
        return "修改";
      }
      return "审核";
    },
    showBanModal(product) {
      this.banParam.ids.splice(0);
      this.banParam.ids.push(product.id);
      this.banParam.bannedDesc = product.bannedDesc;
      this.status.banModal.isShow = true;
    },
    hideBanModal() {
      this.status.banModal.isShow = false;
    },
    banProduct() {
      let self = this;
      self.$Modal.confirm({
        title: "确认",
        content: "确定要屏蔽此产品吗？",
        onOk() {
          banProducts(self);
        }
      });
    },
    cancelBanProduct(product) {
      this.banParam.ids.splice(0);
      this.banParam.ids.push(product.id);
      this.banParam.reason = null;
      let self = this;
      self.$Modal.confirm({
        title: "确认",
        content: "确定要取消屏蔽此产品吗？",
        onOk() {
          cancelBanProducts(self);
        }
      });
    },
    showModifyModal(product) {
      let params = {id: product.id};
      this.$Spin.show();
      this.$apiImpProduct.queryProduct(params).then(response => {
        this.$Spin.hide();
        if(response.success) {
          this.$refs.impProductForm.resetFields();
          this.initProductParam(response.result);
          productData.tStatus.modifyModal.isShow = true;
        }else{
          console.log(response.errorMessage);
          this.$Message.error("查询产品信息失败！");
        }
      }).catch(() => {
        this.$Spin.hide();
        this.$Message.error("查询产品信息失败！");
      });
    },
    initProductParam(product) {
      this.productParam.id = product.id;
      this.productParam.createTime = product.createTime;
      this.productParam.title = product.title;
      this.productParam.titleEn = product.titleEn;
      this.productParam.from = product.from;
      this.productParam.author = product.author;
      this.productParam.sourceUrl = product.sourceUrl;
      this.productParam.pCode = product.pCode;
      this.productParam.shippingFee = product.shippingFee;
      // this.productParam.weight = product.weight;
      if(product.weight==''||product.weight==null){
        let weight = this.getWeightAttrs(product.attrs);
        if(weight.length>0){
          let weightValue = weight[0].value.toLowerCase().trim();
          if(weightValue.endsWith('kg')){
            this.productParam.weight = weightValue.replaceAll("kg",'').trim()*1000+50;
          }else if(weightValue.toLowerCase().endsWith('g')){
            this.productParam.weight = weightValue.replaceAll("g")+50;
          }
        }else{
          this.productParam.weight = 1000;
        }
      }else{
        this.productParam.weight = product.weight;
      }

      this.productParam.state = product.state;
      this.productParam.hasBanned = product.hasBanned;
      this.productParam.priceUnit = isEmpty(product.priceUnit)?"piece":product.priceUnit;
      this.productParam.prices.splice(0);
      this.productParam.prices.push(...product.prices);
      this.productParam.videos.splice(0);
      this.productParam.videos.push(...product.videos);
      //检查是否老产品，没有档位总运费成本
      this.productParam.prices.forEach((item, index) => {
        if(item.shippingCost == null) {
          item.totalShippingCost = null;
          if(item.begin<10){
            item.totalShippingCost=10
          }else if(item.begin>=10 && item.begin<100){
            item.totalShippingCost=30
          }else if(item.begin>=100){
            item.totalShippingCost=100
          }
        }else{
          item.totalShippingCost = this.mulNum(item.shippingCost, item.begin);
        }
      });
      this.productParam.mainImgs.splice(0);
      this.productParam.mainImgs.push(...product.mainImgs);
      this.productParam.productImgs.splice(0);
      if(product.productImgs != null) {
        this.productParam.productImgs.push(...product.productImgs);
      }
      this.productParam.colors.splice(0);
      if(product.colors != null) {
        this.productParam.colors.push(...product.colors);
      }
      //色卡排序
      this.sortColors()
      //属性
      this.productParam.attrs.splice(0);
      if(product.attrs != null) {
        this.productParam.attrs.push(...product.attrs);
      }
      //其他货源
      this.productParam.otherSourceUrls.splice(0);
      if(product.otherSourceUrls != null) {
        this.productParam.otherSourceUrls.push(...product.otherSourceUrls);
      }
      //分类
      //分类
      this.productParam.categories.splice(0);
      if(product.categories != null) {
        this.productParam.categories.push(...product.categories);
      }else{
        console.log("TEst-----"+this.categoryTreeData);
        this.productParam.categories.push(this.categoryTreeData[0].value);
      }
      //尺码表
      // this.productParam.hasSizeTable = product.hasSizeTable;
      this.productParam.sizeTable.splice(0);
      if(product.sizeTable != null) {
        this.productParam.sizeTable.push(...product.sizeTable);
      }
      //标签
      this.productParam.tags.splice(0);
      this.status.modifyModal.tagList.splice(0);
      this.status.modifyModal.tagList.push(...this.status.modifyModal.defaultTagList);
      if(product.tags != null) {
        this.productParam.tags.push(...product.tags);
        for(let tag of product.tags) {
          let index = this.status.modifyModal.tagList.findIndex(element => element == tag);
          if(index < 0) {
            this.status.modifyModal.tagList.push(tag);
          }
        }
      }

      //品牌
      this.status.modifyModal.brandList.splice(0);
      this.status.modifyModal.brandList.push(...this.status.modifyModal.defaultBrandList)
      if(product.attrs != null && product.attrs.length> 0 && product.attrs[0].name == "品牌") {
        let brand = product.attrs[0].valueEn;
        if(isNotEmpty(brand) && !this.status.modifyModal.brandList.includes(brand)) {
          this.status.modifyModal.brandList.push(brand);
        }
      }

      //审核信息
      if(product.auditInfo != null) {
        this.productParam.auditInfo.auditTime = product.auditInfo.auditTime;
        this.productParam.auditInfo.employeeId = product.auditInfo.employeeId;
        this.productParam.auditInfo.employeeName = product.auditInfo.employeeName;
        this.productParam.auditInfo.desc = product.auditInfo.desc;
      }

      this.productParam.extra = product.extra;
      this.productParam.gender = product.gender;
      if(this.productParam.prices.length==1){
        this.computeSumPrice(0);
      }

    },
    hideModifyModal() {
      productData.tStatus.modifyModal.isShow = false;
    },
    modifyProduct() {
      // productData.tParam.modifyParam.state = productData.dict.stateAuditing; //审核中
      modifyProduct(this, false);
    },
    auditProduct(key) {
      // productData.tParam.modifyParam.state = productData.dict.stateAudited; //审核完成
      switch(key) {
        case "pass":
          modifyProduct(this, true);
          break;
      }
    },
    modifyProductAfterAudited() {
      modifyProduct(this, false);
    },
    importProductAfterAudited(key) {
      switch (key) {
        case "import":
          modifyProduct(this, true);
          break;
      }
    },
    deleteProduct(id) {
      let self = this;
      self.$Modal.confirm({
        title: "删除确认",
        content: "确定要删除此产品吗？",
        okText: "确定",
        cancelText: "取消",
        onOk() {
          deleteProduct(self, id);
        },
        onCancel() {
          productData.tStatus.modifyModal.isShow = false;
        }
      })
    },
    changeSelectedRows(selection) {
      this.selectedRows.splice(0);
      this.selectedRows.push(...selection);
    },
    changeTimeParam(dateArr, type) {
      if(isNotEmpty(dateArr[0])){
        this.searchParam.startTime = this.$tiyQueryTime(new Date(dateArr[0]+' 00:00:00').getTime());
        this.searchParam.endTime = this.$tiyQueryTime(new Date(dateArr[1]+' 23:59:59').getTime());
      }
    },
    clearTimeParam() {
      this.searchParam.startTime = null;
      this.searchParam.endTime = null;
    },
    search() {
      productData.tPage.listPage.pageNum = 1;
      queryProductList(this);
    },
    pageNumChange(pageNum) {
      productData.tPage.listPage.pageNum = pageNum;
      queryProductList(this);
    },
    pageSizeChange(pageSize) {
      productData.tPage.listPage.pageNum = 1;
      productData.tPage.listPage.pageSize = pageSize;
      queryProductList(this);
    },
    deleteImage(type, index) {//type: 1.主图, 2.详情图, 3.色卡图, 4.色卡明细图
      if(type == 1) {
        this.productParam.mainImgs.splice(index, 1);
        return;
      }
      if(type == 2) {
        this.productParam.productImgs.splice(index, 1);
      }
      if(type == 3) {
        this.colorParam.colorImg = "";
      }
      if(type == 4) {
        this.colorParam.detailImgs.splice(index, 1);
      }
    },
    addPrice() {
      // let begin = this.productParam.prices.length>0?this.productParam.prices[this.productParam.prices.length-1].begin:0;
      this.productParam.prices.push({begin: null, end: null, price: 0});
    },
    deletePrice(index) {
      if(this.productParam.prices.length > 1) {
        this.productParam.prices.splice(index, 1);
      }
    },
    addAttribute() {
      this.productParam.attrs.push({name: "", value: "", nameEn: "", valueEn: ""});
    },
    deleteAttribute(index) {
      this.productParam.attrs.splice(index, 1);
    },
    showModifyColorModal(index) {
      this.initProductColorParam(this.productParam.colors[index]);
      this.status.modifyColorModal.colorIndex = index;
      this.status.modifyColorModal.isShow = true;
    },
    hideModifyColorModal() {
      this.status.modifyColorModal.isShow = false;
    },
    initProductColorParam(color) {
      productData.tParam.colorParam.name = color.name;
      productData.tParam.colorParam.nameEn = color.nameEn;
      productData.tParam.colorParam.position = color.position;
      productData.tParam.colorParam.colorImg = color.colorImg;
      productData.tParam.colorParam.imgOriginal = color.imgOriginal;
      productData.tParam.colorParam.detailImgs.splice(0);
      if(color.detailImgs != null) {
        productData.tParam.colorParam.detailImgs.push(...color.detailImgs);
      }
      productData.tParam.colorParam.sizes.splice(0);
      productData.tParam.colorParam.sizes.push(...color.sizes);
    },
    deleteProductColor(index) {
      let self = this;
      self.$Modal.confirm({
        title: "确认",
        content: "确定要删除此色卡吗？",
        okText: "确定",
        cancelText: "取消",
        onOk() {
          productData.tParam.modifyParam.colors.splice(index, 1);
        },
      });
    },
    modifyProductColor() {
      let color = productData.tParam.modifyParam.colors[this.status.modifyColorModal.colorIndex];
      color.name = productData.tParam.colorParam.name;
      color.nameEn = productData.tParam.colorParam.nameEn;
      color.position = productData.tParam.colorParam.position;
      color.colorImg = productData.tParam.colorParam.colorImg;
      color.imgOriginal = productData.tParam.colorParam.imgOriginal;
      color.detailImgs.splice(0);
      if(productData.tParam.colorParam.detailImgs != null) {
        color.detailImgs.push(...productData.tParam.colorParam.detailImgs);
      }
      color.sizes.splice(0);
      color.sizes.push(...productData.tParam.colorParam.sizes);
      this.sortColors();
      this.status.modifyColorModal.isShow = false;
    },
    moveToFirst(imgs, index) {
      let img = imgs[index];
      imgs.splice(index, 1);
      imgs.splice(0, 0, img);
    },
    getListImgUrl(imgOriginal, item) {
      if(this.isItemAuditing(item) || this.isItemAudited(item)) {
        let imgUrl = imgOriginal.substring(0, imgOriginal.lastIndexOf("/"))+"/200w"+imgOriginal.substring(imgOriginal.lastIndexOf("/"));
        return this.yunPath + imgUrl;
      }
      return this.yunPath + imgOriginal + "?v="+this.imgParam;
    },
    showBigImage(imgSrc) {
      this.bigImage.src = imgSrc;
      this.bigImage.isShow = true;
    },
    deleteSize(index) {
      this.colorParam.sizes.splice(index, 1);
    },
    addSize() {
      this.colorParam.sizes.push({name: "", nameEn: "", stock: 0});
    },
    modifyOtherColorSizes(sizeName, sizeNameEn) {
      for(let i=0; i<productData.tParam.modifyParam.colors.length; i++) {
        for(let j=0; j<productData.tParam.modifyParam.colors[i].sizes.length; j++) {
          if(productData.tParam.modifyParam.colors[i].sizes[j].name == sizeName) {
            productData.tParam.modifyParam.colors[i].sizes[j].nameEn = sizeNameEn;
            break;
          }
        }
      }
    },
    deleteColorSize(sizes, index) {
      let self = this;
      let sizeName = sizes[index].name;
      if(isEmpty(sizeName)) {
        sizes.splice(index, 1);
        return;
      }
      self.$Modal.confirm({
        title: "提示",
        content: "是否同步删除其他色卡的同名尺码？",
        okText: "是",
        cancelText: "否",
        onOk() {
          for(let i=0; i<productData.tParam.modifyParam.colors.length; i++) {
            for(let j=0; j<productData.tParam.modifyParam.colors[i].sizes.length; j++) {
              if(productData.tParam.modifyParam.colors[i].sizes[j].name == sizeName) {
                productData.tParam.modifyParam.colors[i].sizes.splice(j, 1);
                break;
              }
            }
          }
        },
        onCancel() {
          sizes.splice(index, 1);
        }
      })
    },
    addColorSize(sizes) {
      sizes.push({name: "", nameEn: "", stock: 0});
    },
    getProductWeight(item) {
      if(item.weight == null) {
        return "无";
      }
      return item.weight+'g';
    },
    getHasSizeTable(item) {
      if(item.sizeTable == null || item.sizeTable.length == 0) {
        return "无";
      }
      return "有";
    },

    getProductState(product) {
      let element = productData.dict.productStates.find(element => element.value == product.state);
      return element==null?"":element.label;
    },
    /*importToFormalLib() {
      if(this.selectedRows == null || this.selectedRows.length == 0) {
        this.$Message.warning("请选择要导入的产品！");
        return;
      }
      let ids = this.selectedRows.map(row => {return row.id});
      importToFormalLib(this, ids);
    },*/
    createTag(input) {
      productData.tStatus.modifyModal.tagList.push(input);
    },
    saveProductTags() {
      saveProductTags(this);
    },
    changeHasSizeTable() {
      let self = this;
      return new Promise((resolve) => {
        // if(productData.tParam.modifyParam.hasSizeTable) {
          self.$Modal.confirm({
            title: "提示",
            content: "关闭尺码表会清空尺码表所有内容",
            okText: "继续关闭",
            cancelText: "取消",
            onOk() {
              productData.tParam.modifyParam.sizeTable.splice(0);
              resolve();
            },
          })
        // }else{
        //   resolve();
        // }
      });
    },
    addSizeTable() {
      // productData.tParam.modifyParam.hasSizeTable = true;
    },
    deleteSizeTable() {
      // if(productData.tParam.modifyParam.hasSizeTable) {
        this.$Modal.confirm({
          title: "确认",
          content: "确定要删除尺码表吗？",
          okText: "删除",
          onOk() {
            // productData.tParam.modifyParam.hasSizeTable = false;
            productData.tParam.modifyParam.sizeTable.splice(0);
          }
        });
      // }
    },
    yCeil(num, byte){
      let n = Math.pow(10, byte)
      return Math.ceil(num * n) / n
    },
    computeSumPrice(index) {
      let self = this;
      let price = isEmpty(this.productParam.prices[index].price)?0:this.productParam.prices[index].price;
      let totalShippingCost = isEmpty(this.productParam.prices[index].totalShippingCost)?0:this.productParam.prices[index].totalShippingCost;
      let amount = isEmpty(this.productParam.prices[index].begin)?1:this.productParam.prices[index].begin;
      let shippingCost = this.yCeil((totalShippingCost*1.0/amount).toFixed(2),1);
      let usdPrice = self.mulNum(self.addNum(price, shippingCost), 0.2);//(价格+运费成本)*1.2/6
      self.productParam.prices[index].shippingCost = shippingCost;
      self.productParam.prices[index].usdPrice = usdPrice;
    },
    addNum(arg1, arg2) {
      let r1 = 0;
      let r2 = 0;
      let m = 0;
      try {
        r1 = arg1.toString().split(".")[1].length;
      } catch (e) {
        r1 = 0;
      }

      try {
        r2 = arg2.toString().split(".")[1].length;
      } catch (e) {
        r2 = 0;
      }

      m = Math.pow(10, Math.max(r1, r2));
      let result = (arg1 * m + arg2 * m) / m;
      return result;
    },
    // mulNum(arg1, arg2) {
    //   let r1 = Number(arg1.toString().replace(".", ""));
    //   let r2 = Number(arg2.toString().replace(".", ""));
    //   let m = 0;
    //
    //   try {
    //     m += arg1.toString().split(".")[1].length;
    //   } catch (e) {
    //     m += 0;
    //   }
    //
    //   try {
    //     m += arg2.toString().split(".")[1].length;
    //   } catch (e) {
    //     m += 0;
    //   }
    //   let result = (r1 * r2) / Math.pow(10, m);
    //   return result;
    // },
    mulNum(arg1,arg2) {
      let r1 = Number(arg1.toString().replace(".", ""))+150;

      return (r1/6.7).toFixed(1);
    },
    showProductImageSelection(type) {//type: 1.主图, 2.详情图, 3.色卡图, 4.色卡明细图
      this.productCode = this.productParam.pCode;
      this.status.imageSelectModal.type = type;
      this.status.imageSelectModal.isShow = true;
    },
    hideProductImageSelection() {
      this.status.imageSelectModal.isShow = false;
    },
    isSingleSelect(type) {
      return type == 3; //色卡图是单选，其他是多选
    },
    selectImages(images) {
      if(this.status.imageSelectModal.type == 3) {//色卡图
        this.colorParam.colorImg = images[0];
      }
      if(this.status.imageSelectModal.type == 4) {//色卡明细图
        this.colorParam.detailImgs.push(...images);
      }
      this.status.imageSelectModal.isShow = false;
    },
    sortColors() {
      productData.tParam.modifyParam.colors.sort(function (a, b){
        return a.position - b.position;
      });
    },
    getWeightAttrs(attrs) {
      if(attrs == null || attrs.length == 0) {
        return [];
      }
      let weightAttrs = attrs.filter(attr => isNotEmpty(attr.nameEn) && attr.nameEn.toLowerCase().indexOf("weight")>0);
      if(weightAttrs==null || weightAttrs.length == 0) {
        return [];
      }else{
        return weightAttrs;
      }
    },
    removeNonExistImages(product) {
      let self = this;
      this.$Modal.confirm({
        title: "确认",
        content: "确定要清空未上传到服务器的图片吗？",
        onOk() {
          removeNonExistImages(self, product);
        }
      });
    },
    uploadProgress(event, file, fileList) {
      this.$Spin.show();
    },
    uploadSuccess(response, file, fileList) {
      this.$Spin.hide();
      this.imgParam = new Date().getTime();
      if(response.success) {
        this.$Message.success("上传完成");
      }else{
        this.$Modal.error({title: "提示", content: "图片"+response.result.join(", ")+"上传失败！"})
      }
    },
    uploadError(error, file, fileList) {
      console.error(error);
      this.$Spin.hide();
      this.$Message.error("上传失败！");
    },
    recollectImages() {
      recollectImages(this, this.productParam.id);
    },
    belongToCurrentStation(prouct) {
      if(prouct.createStation == null) {
        return false;
      }
      return prouct.createStation.code == this.station.code;
    },
    isNotEmpty(val) {
      return isNotEmpty(val);
    },
    showImportDialog(item) {
      resetImportParams([item.id]);
      this.importStatus.isShow = true;
    },
    hideImportDialog() {
      this.importStatus.isShow = false;
    },
    importProducts() {
      importProducts(this);
    },
    isBrandsAttr(attr) {
      return attr.name == "品牌" || attr.nameEn == "Brands";
    },
    createBrand(input) {
      productData.tStatus.modifyModal.brandList.push(input);
    },
    changeBrand(brand, item) {
      item.value = brand;
    },
    testImport() {
      let testData = { "from": "1688", "store": { "shopName": "广州市天河区森罗服装商行", "shopUrl": "https://shop741do3f528131.1688.com", "shopId": "shop741do3f528131", "years": "1", "location": "广东 广州", "sellerName": "程思龙", "sellerChat": "https://me.1688.com/*xC-i2FIyvFNSvFxSvmxSMmNyZDHYvQTT.html" }, "author": "tiy", "sourceUrl": "https://detail.1688.com/offer/649187724887.html", "pCode": "649187724887", "title": "特别给力的原厂渠道~真丝拼接T恤女印花夏季桑蚕丝短袖薄款上衣", "prices": [ { "begin": "2", "end": "499", "price": "38.50" }, { "begin": "500", "end": "999", "price": "36.50" }, { "begin": "1000", "end": "", "price": "34.50" } ], "shippingFee": "7", "colors": [ { "name": "黑色", "colorImg": "649187724887/", "position": 0, "imgOriginal": "", "sizes": [ { "name": "M", "stock": "2924" }, { "name": "L", "stock": "2920" }, { "name": "XL", "stock": "2911" }, { "name": "XXL", "stock": "2956" } ] }, { "name": "卡其色", "colorImg": "649187724887/", "position": 1, "imgOriginal": "", "sizes": [ { "name": "M", "stock": "2924" }, { "name": "L", "stock": "2920" }, { "name": "XL", "stock": "2911" }, { "name": "XXL", "stock": "2956" } ] }, { "name": "白色", "colorImg": "649187724887/", "position": 2, "imgOriginal": "", "sizes": [ { "name": "M", "stock": "2924" }, { "name": "L", "stock": "2920" }, { "name": "XL", "stock": "2911" }, { "name": "XXL", "stock": "2956" } ] } ], "attrs": [ { "name": "跨境包裹重量", "value": "0.3 kg" }, { "name": "单位重量", "value": "0.3 kg" }, { "name": "面料名称", "value": "聚酯纤维" }, { "name": "主面料成分", "value": "聚酯纤维（涤纶）" }, { "name": "主面料成分的含量", "value": "100%" }, { "name": "主面料成分2", "value": "聚酯纤维（涤纶）" }, { "name": "主面料成分2的含量", "value": "100%" }, { "name": "里料成分", "value": "聚酯纤维（涤纶）" }, { "name": "里料成分含量", "value": "100%" }, { "name": "图案", "value": "印花" }, { "name": "风格", "value": "休闲" }, { "name": "款式", "value": "套头" }, { "name": "袖长", "value": "短袖" }, { "name": "工艺", "value": "印花/印染" }, { "name": "版型", "value": "宽松型" }, { "name": "衣长", "value": "普通款(50cm＜衣长≤65cm)" }, { "name": "领型", "value": "圆领" }, { "name": "袖型", "value": "常规袖" }, { "name": "适合年龄", "value": "18-24周岁" }, { "name": "风格类型", "value": "都市休闲" } ], "mainImgs": [ { "colorImg": "649187724887/main_0.jpg", "imgOriginal": "https://cbu01.alicdn.com/img/ibank/O1CN01BUW81K218ZNqplAEk_!!2210916906940-0-cib.jpg" }, { "colorImg": "649187724887/main_1.jpg", "imgOriginal": "https://cbu01.alicdn.com/img/ibank/O1CN01XjmdgK218ZO4k0mlV_!!2210916906940-0-cib.jpg" }, { "colorImg": "649187724887/main_2.jpg", "imgOriginal": "https://cbu01.alicdn.com/img/ibank/O1CN01zLKuqu218ZO2JmLdy_!!2210916906940-0-cib.jpg" }, { "colorImg": "649187724887/main_3.jpg", "imgOriginal": "https://cbu01.alicdn.com/img/ibank/O1CN01JynLAf218ZO71vhKO_!!2210916906940-0-cib.jpg" }, { "colorImg": "649187724887/main_4.jpg", "imgOriginal": "https://cbu01.alicdn.com/img/ibank/O1CN01E7LXd2218ZNxWrk46_!!2210916906940-0-cib.jpg" } ], "productImgs": [ { "colorImg": "649187724887/products_0.jpg", "imgOriginal": "https://cbu01.alicdn.com/img/ibank/O1CN01SYXFbv218ZMg7TvVQ_!!2210916906940-0-cib.jpg" }, { "colorImg": "649187724887/products_1.jpg", "imgOriginal": "https://cbu01.alicdn.com/img/ibank/O1CN01AeBmdT218ZMf1raAp_!!2210916906940-0-cib.jpg" }, { "colorImg": "649187724887/products_2.jpg", "imgOriginal": "https://cbu01.alicdn.com/img/ibank/O1CN01NOUWaB218ZNxX000A_!!2210916906940-0-cib.jpg" }, { "colorImg": "649187724887/products_3.jpg", "imgOriginal": "https://cbu01.alicdn.com/img/ibank/O1CN01UeHJbb218ZNvU5e0Q_!!2210916906940-0-cib.jpg" }, { "colorImg": "649187724887/products_4.jpg", "imgOriginal": "https://cbu01.alicdn.com/img/ibank/O1CN01LmyUZM218ZO19YTut_!!2210916906940-0-cib.jpg" }, { "colorImg": "649187724887/products_5.jpg", "imgOriginal": "https://cbu01.alicdn.com/img/ibank/O1CN01CHIvW2218ZO3iw0AD_!!2210916906940-0-cib.jpg" }, { "colorImg": "649187724887/products_6.jpg", "imgOriginal": "https://cbu01.alicdn.com/img/ibank/O1CN01iwzwEz218ZO4kBOLy_!!2210916906940-0-cib.jpg" }, { "colorImg": "649187724887/products_7.jpg", "imgOriginal": "https://cbu01.alicdn.com/img/ibank/O1CN0132Innr218ZO6IUOoo_!!2210916906940-0-cib.jpg" }, { "colorImg": "649187724887/products_8.jpg", "imgOriginal": "https://cbu01.alicdn.com/img/ibank/O1CN01wBd0y8218ZMV2gds2_!!2210916906940-0-cib.jpg" } ] };
      let url = "http://192.168.31.58:8081/adminServer/product/supply/import";
      // let url = "http://admin.11wholesale.com:8080/adminServer/product/supply/import";
      let self = this;
      axios.post(url, qs.stringify({json: JSON.stringify(testData)})).then(response => {
        console.log(response.data);
        queryProductList(self);
      })
    },
    toggleAllCheck(isChecked) {
      this.selectedIds.splice(0);
      if(isChecked) {
        let self = this;
        let ids = this.productList.filter(row => !self.hasBanned(row)).map(row => {return row.id});
        this.selectedIds.push(...ids);
      }
    },
    hasBanned(product) {
      let has = product.hasBanned || this.containsStation(product.bannedStations);
      return has;
    },
    containsStation(stations) {
      if(stations == null || stations.length == 0) {
        return false;
      }
      let station = stations.find(station => station.code == this.station.code);
      if(station == null) {
        return false;
      }else{
        return true;
      }
    },
    batchUpdate(){
      if(this.selectedIds.length==0){
        return;
      }
      modifyBatchUpdateProduct(this,true);
    }
  },
  watch: {
    selectedIds() {
      if(this.selectedIds.length > 0) {
        if(this.selectedIds.length == this.productList.length) {
          this.allCheck.isChecked = true;
          this.allCheck.indeterminate = false;
        }else{
          this.allCheck.isChecked = false;
          this.allCheck.indeterminate = true;
        }
      }else{
        this.allCheck.isChecked = false;
        this.allCheck.indeterminate = false;
      }
    },
  },
  mounted() {
    queryMongoCategories(this, this.categoryTreeData);
    initPageInfo();
  }
}
</script>

<style scoped lang="less">
@import  (once,optional)  "../css/base.less";
.data-list {
  margin: 1rem 0rem;
  line-height: 25px;
}
.list-item {
  .flex-colum-wrap;
  justify-items: left;
  align-items: start;
  .item-top{
    width: 100%;
    margin-bottom: 5px;
    .flex-row-wrap;
    justify-content: space-between;
  }
  .item-content {
    margin-bottom: 35px;
    text-align: left;
  }
  .item-bottom{
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    display: block;
    //padding: 0 1rem 0.5rem 0;
    cursor: pointer;
    text-align: right;
    button {
      margin-left: 0.5rem;
    }
  }
}
.modal_base_div {
  text-align: left;
  margin-top: 20px;
  padding: 20px;
  border: dotted thin #d1d1d1
}

.modal_base_div_title {
  font-weight: bold;
  text-align: left;
  margin-bottom: 20px
}
.one-line {
  width: 100%;
}
.image-card {
  width: 180px;
  height:200px;
  display: inline-block;
  margin: 10px;
  .image-box {
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
    img {
      max-width: 100%;
      max-height: 100%;
      vertical-align: middle;
    }
  }
  .extra {
    background-color: #ffffff;
    border: 1px solid #ccc;
    cursor: pointer;
    width: 24px;
    height: 24px;
    line-height: 22px;
    border-radius: 13px;
    text-align: center;
    .ivu-icon {
      font-size: 16px;
    }
  }
}
.ivu-card-extra {
  top: 10px !important;
  right: 10px !important;
}
.item-label {
  font-weight: bold;
  font-size: 14px;
}
.item-name {
  display: inline-block;
  text-align: right;
}
.item-name-count {
  width: 60px;
}
.item-name-price {
  width: 120px;
}
.item-size-name {
  display: inline-block;
  width: 80px;
}
.item-input {
  width: 300px;
  margin-right: 10px;
}
.item-input-large {
  width: 800px;
  margin-right: 10px;
}
.item-input-common {
  width: 240px;
  margin-right: 10px;
}
.item-input-small {
  width: 150px;
  margin-right: 10px;
}
.item-input-mini {
  width: 80px;
  margin-right: 10px;
}
.attr-item {
  display: inline-block;
  width: 400px;
  margin-right: 10px;
}
.attr-name {
  display: inline-block;
  width: 60px;
  text-align: right;
}
.item-button {
  display: inline-block;
  vertical-align: top;
}
.form-button {
  margin-top: 20px;
  text-align: center;
}
.big-img-box {
  width: 100%;
  min-height: 500px;
  text-align: center;
}
.big-img-box img {
  max-width: 100%;
  vertical-align: middle;
}
.under-tip {
  padding-left: 5px;
  color:#888;
  font-size: 11px;
}
.size-item {
  display: inline-block;
  width: 250px;
  margin-right: 10px;
  vertical-align: top;
}
.size-name {
  display: inline-block;
  width: 80px;
  text-align: right;
}
.color-buttons {
  margin-top: 20px;
  text-align: center;
  button {
    margin-top: 10px;
  }
}
</style>
